package main

import (
	"supershare/backend/models"
	"supershare/backend/utils"
	"time"

	"github.com/beego/beego/v2/client/orm"
	"github.com/beego/beego/v2/core/logs"
	"github.com/beego/beego/v2/server/web"
)

func init() {
	// 初始化配置
	web.LoadAppConfig("ini", "conf/app.conf")

	// 初始化数据库
	models.InitDB()

	// 配置日志
	logs.SetLogger(logs.AdapterFile, `{"filename":"logs/meituan_sync.log","level":7,"maxlines":0,"maxsize":0,"daily":true,"maxdays":10}`)
}

func main() {
	logs.Info("启动美团订单同步任务...")

	// 获取所有启用的美团配置
	o := models.GetOrm()
	var configs []*models.Meituan
	_, err := o.QueryTable(new(models.Meituan)).
		Filter("status", 1).
		Filter("is_deleted", 0).
		All(&configs)

	if err != nil {
		logs.Error("获取美团配置失败: %v", err)
		return
	}

	logs.Info("找到 %d 个美团配置需要同步", len(configs))

	// 遍历所有配置，同步订单
	for _, config := range configs {
		syncMeituanOrders(config)
	}

	logs.Info("美团订单同步任务完成")
}

// 同步单个美团配置的订单
func syncMeituanOrders(config *models.Meituan) {
	logs.Info("开始同步门店[%s]的美团订单...", config.StoreName)

	// 创建美团API客户端
	meituanAPI := utils.NewMeituanAPI(config.AppKey, config.AppSecret, config.PoiId)

	// 计算同步时间范围
	endTime := time.Now()
	// unix时间戳config.LastSyncTime 转 time.Time
	startTime := time.Unix(config.LastSyncTime, 0)
	if startTime.IsZero() {
		// 如果没有上次同步时间，则默认同步最近24小时的订单
		startTime = endTime.Add(-24 * time.Hour)
	}

	// 获取美团订单
	logs.Info("从 %s 到 %s 的订单", startTime.Format("2006-01-02 15:04:05"), endTime.Format("2006-01-02 15:04:05"))
	orders, err := meituanAPI.GetOrders(startTime, endTime)
	if err != nil {
		logs.Error("获取美团订单失败: %v", err)
		return
	}

	logs.Info("获取到 %d 个美团订单", len(orders))

	// 处理订单
	o := models.GetOrm()
	for _, orderData := range orders {
		processOrder(o, config, orderData)
	}

	// 更新最后同步时间
	config.LastSyncTime = endTime.Unix()
	err = models.UpdateMeituan(config)
	if err != nil {
		logs.Error("更新最后同步时间失败: %v", err)
	}

	logs.Info("门店[%s]的美团订单同步完成", config.StoreName)
}

// 处理单个订单
func processOrder(o orm.Ormer, config *models.Meituan, orderData map[string]interface{}) {
	// 提取订单ID
	orderId, ok := orderData["order_id"].(string)
	if !ok || orderId == "" {
		logs.Error("订单ID无效")
		return
	}

	// 检查订单是否已存在
	existingOrder, err := models.GetMeituanOrderByOrderId(orderId)
	if err != nil {
		logs.Error("检查订单是否存在失败: %v", err)
		return
	}

	if existingOrder != nil {
		logs.Info("订单 %s 已存在，跳过", orderId)
		return
	}

	// 提取订单数据
	orderType := 0
	if t, ok := orderData["order_type"].(float64); ok {
		orderType = int(t)
	}

	totalAmount := int64(0)
	if amount, ok := orderData["total"].(float64); ok {
		totalAmount = int64(amount * 100) // 转换为分
	}

	payment := int64(0)
	if p, ok := orderData["payment"].(float64); ok {
		payment = int64(p * 100) // 转换为分
	}

	customerName := ""
	if name, ok := orderData["customer_name"].(string); ok {
		customerName = name
	}

	customerPhone := ""
	if phone, ok := orderData["customer_phone"].(string); ok {
		customerPhone = phone
	}

	customerCount := 0
	if count, ok := orderData["customer_count"].(float64); ok {
		customerCount = int(count)
	}

	bookingTime := time.Now()
	if bookingTimeStr, ok := orderData["booking_time"].(string); ok {
		parsedTime, err := time.ParseInLocation("2006-01-02 15:04:05", bookingTimeStr, time.Local)
		if err == nil {
			bookingTime = parsedTime
		}
	}

	bookingEndTime := bookingTime.Add(2 * time.Hour) // 默认2小时
	if durationMinutes, ok := orderData["duration"].(float64); ok && durationMinutes > 0 {
		bookingEndTime = bookingTime.Add(time.Duration(durationMinutes) * time.Minute)
	}

	remark := ""
	if r, ok := orderData["remark"].(string); ok {
		remark = r
	}

	// 创建订单记录
	order := &models.MeituanOrder{
		MeituanId:      config.Id,
		StoreId:        config.StoreId,
		OrderId:        orderId,
		OrderStatus:    0, // 未处理
		OrderType:      orderType,
		TotalAmount:    totalAmount,
		Payment:        payment,
		CustomerName:   customerName,
		CustomerPhone:  customerPhone,
		CustomerCount:  customerCount,
		BookingTime:    bookingTime.Unix(),
		BookingEndTime: bookingEndTime.Unix(),
		Remark:         remark,
		IsProcessed:    0,
	}

	// 保存到数据库
	id, err := models.AddMeituanOrder(order)
	if err != nil {
		logs.Error("保存美团订单失败: %v", err)
		return
	}

	logs.Info("成功添加美团订单, ID: %d, 订单号: %s", id, orderId)
}
